package cn.wolfcode.config;

import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

@Setter
@Getter
//@ServerEndpoint注解和我们之前学过的@RequestMapping注解作用很相似,只不过是接收的的是ws协议的请求
@ServerEndpoint("/{token}")
@Component
public class WebSocketServer {
    private Session session;
    public static ConcurrentHashMap<String, WebSocketServer> clients = new ConcurrentHashMap<>();

    /**
     * OnOpen:当我们的客户端可ws成功建立联系后,会执行OnOpen方法
     * OnClose:当我们的客户端和ws断开联系后,会执行OnClose方法
     * OnError:当我们的客户端可ws连接过程中出现异常,会执行OnError方法
     * onMessage:当我们的客户端给服务端发数据,会执行onMessage方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) {
        System.out.println("客户端连接===>" + token);
        this.session = session;
        clients.put(token, this);
    }

    @OnClose
    public void onClose(@PathParam("uuid") String uuid) {
        clients.remove(uuid);
    }

    @OnError
    public void onError(Throwable error) {
        error.printStackTrace();
    }

    @OnMessage
    public void OnMessage(String message) {
        System.out.println(message);
    }
}